package com.yuyou.train.lesson.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.train.lesson.mapper.LessonResourceRuleRelationMapper;
import com.yuyou.train.lesson.service.ILessonResourceRuleFrameService;
import com.yuyou.train.lesson.service.ILessonResourceRuleRelationService;
import com.yuyou.train.lesson.service.ILessonService;
import com.yuyou.train.lesson.service.IResourceExamService;
import com.yuyou.train.lesson.service.IResourceQuestionService;
import com.yuyou.train.lesson.service.IResourceService;
import com.yuyou.train.lesson.service.IRuleService;
import com.yuyou.train.service.api.lesson.dto.ResourceDetailDTO;
import com.yuyou.train.service.api.lesson.entity.Lesson;
import com.yuyou.train.service.api.lesson.entity.LessonResourceRuleFrame;
import com.yuyou.train.service.api.lesson.entity.LessonResourceRuleRelation;
import com.yuyou.train.service.api.lesson.entity.ResourceExam;
import com.yuyou.train.service.api.lesson.entity.ResourceQuestion;
import com.yuyou.train.service.api.lesson.entity.Rule;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.entity.UserHw;
import com.yuyou.train.service.api.user.entity.UserHwTeacher;
import com.yuyou.train.service.api.user.entity.UserLessonProgress;
import com.yuyou.train.service.api.user.service.UserAPI;
import com.yuyou.train.service.api.user.service.UserHwAPI;
import com.yuyou.train.service.api.user.service.UserLessonProgressAPI;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.constant.user.UserLessonProgressCons;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.lesson.LessonEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.enums.user.UserLessonProgressEnums;
import com.yuyou.train.util.message.lesson.LessonMess;
import com.yuyou.train.util.tool.Sequence;
import com.yuyou.train.util.tool.UUIDUtil;

@Service
public class LessonResourceRuleRelationServiceImpl implements ILessonResourceRuleRelationService{

	@Autowired
	private LessonResourceRuleRelationMapper lesResRuleRelMapperp;
	
	@Autowired
	private IResourceService resourceService;
	
	@Autowired
	private ILessonResourceRuleFrameService lesResRulFraService;
	
	@Autowired
	private ILessonService lessonService;
	
	@Autowired
	private IRuleService ruleService;
	
	@Autowired
	private IResourceExamService resourceExamService;
	
	@Autowired
	private UserLessonProgressAPI userLessonProgressAPI;
	
	@Autowired
	private UserAPI userAPI;
	
	@Autowired
	private UserHwAPI userHwAPI;
	
	@Autowired
	private IResourceQuestionService resourceQuestionService;
	
	@Override
	public int deleteByPrimaryKey(String id) {		
		return lesResRuleRelMapperp.deleteByPrimaryKey(id);
	}
	
	@Override
	public int deleteByLessonId(String lessonId) {
		return lesResRuleRelMapperp.deleteByLessonId(lessonId);
	}

	@Override
	public int insert(LessonResourceRuleRelation record) {
		record.setId(Sequence.getSequence().getNextId());
		record.setCreateTime(new Date());
		return lesResRuleRelMapperp.insert(record);
	}

	@Override
	public LessonResourceRuleRelation selectByPrimaryKey(String id) {
		return lesResRuleRelMapperp.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(LessonResourceRuleRelation record) {
		return lesResRuleRelMapperp.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<LessonResourceRuleRelation> findLesResRuleRel(
			LessonResourceRuleRelation record) {
		return lesResRuleRelMapperp.findLesResRuleRel(record);
	}

	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<String> setRelation(LessonResourceRuleRelation record,
			List<LessonResourceRuleFrame> frameList) {
		//课程启用不能修改
		ResBoolSimpleInfo<String> res=lessonService.isLessonUse(record.getLessonId());
		if(!res.isSuccess()){
			return res;
		}
				
		//叶子才能添加资源关系
		Lesson lesson=lessonService.selectByPrimaryKey(record.getLessonId());
		if(lesson.getIsLeaf().equals(CommEnums.isLeaf.no.getValue())){
			return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_LEAF_ADD_RELATION);
		}	
			
		ResourceDetailDTO resource=resourceService.selectByPrimaryKey(record.getResourceId());
		Rule rule=ruleService.selectByPrimaryKey(record.getRuleId());
		
		//规则未启用
		if(rule.getIsUse().equals(CommEnums.isUse.no.getValue())){
			return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_RULE_IS_USE);
		}
			
		//试卷是否启用
		if(resource.getResourceType().equals(CommEnums.resourceType.exam.getValue())){
			ResourceExam exam=resourceExamService.selectByPrimaryKey(resource.getResourceExamId());
			if(exam.getIsUse().equals(CommEnums.isUse.no.getValue())){
				return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_EXAM_IS_USE);
			}
		}
		
		//资源规则是否相同
		if(!resource.getResourceType().equals(rule.getResourceType())){
			return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_RESOURCE_TYPE);
		}
		
		//假如是考核节点，resource_type必须是05：作业（自评作业），规则必须要老师打分
		if(lesson.getAttr().equals(LessonEnums.attr.check.getValue())){
			if(!resource.getResourceType().equals(CommEnums.resourceType.hwNeedComment.getValue())){
				return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_UPDATE_ATTR_CHECK);
			}
			if(rule.getNeedScore()==null){
				return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_UPDATE_ATTR_CHECK);
			}		
		}
		
		//关系已经设立，不能重设
		LessonResourceRuleRelation rel=this.selectByLessonId(record.getLessonId());
		if(rel!=null){
			return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_UPDATE_RESOURCE_RULE);
		}

		//帧
		if(frameList!=null&&resource.getResourceType().equals(CommEnums.resourceType.video.getValue())){
			//判断题目存在和状态
			for(LessonResourceRuleFrame frame:frameList){
				ResourceQuestion question=resourceQuestionService.selectByPrimaryKey(frame.getResourceQuestionId());
				if(question==null || question.getIsUse().equals(CommEnums.isUse.no.getValue())){
					return new ResBoolSimpleInfo<String>(false,LessonMess.ERR_QUESTION_IS_USE);
				}
			}
			
			//删除再添加
			lesResRulFraService.deleteByLessonId(record.getLessonId());
			int sort=0;
			for(LessonResourceRuleFrame frame:frameList){								
				LessonResourceRuleFrame insertFra=new LessonResourceRuleFrame();
				insertFra.setLessonId(record.getLessonId());
				insertFra.setResourceQuestionId(frame.getResourceQuestionId());
				insertFra.setSort(++sort);
				insertFra.setSecond(frame.getSecond());
				lesResRulFraService.insert(insertFra);
			}

		}
		
		//删除再添加
		this.deleteByLessonId(record.getLessonId());
		this.insert(record);
		
		return new ResBoolSimpleInfo<String>(true,null,record.getLessonId());
	}

	@Override
	public LessonResourceRuleRelation selectByLessonId(String lessonId) {
		return lesResRuleRelMapperp.selectByLessonId(lessonId);
	}

	@Transactional(timeout=60)
	public ResBoolSimpleInfo<String> delAuditUserLesson(String delLessonId)throws Exception{
		delAuditUserLessonByStatus(delLessonId,UserLessonProgressEnums.status.studying.getValue());
		delAuditUserLessonByStatus(delLessonId,UserLessonProgressEnums.status.Auditing.getValue());
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	
	@Transactional(timeout=60)
	private void delAuditUserLessonByStatus(String delLessonId,String status) throws Exception{
		List<UserLessonProgress> list=userLessonProgressAPI.findUserLessonProgress(delLessonId, status);
		for(UserLessonProgress p:list){										
			lesResRuleRelMapperp.cleanUserLessonProgress(p.getId());	
			insertUserNextLesson(p.getUserId());
			
			//作业类型也要清除
			UserHw userHw=new UserHw();
			userHw.setUserId(p.getUserId());
			userHw.setLessionId(p.getLessonId());
			
			List<UserHw> userHwList=userHwAPI.findUserHw(userHw);
			for(UserHw hw:userHwList){
				lesResRuleRelMapperp.delHwByHwId(hw.getId());
				lesResRuleRelMapperp.delHwPraiseByHwId(hw.getId());
				UserHwTeacher condi=new UserHwTeacher();
				condi.setUserHwId(hw.getId());
				List<UserHwTeacher> teacherList=userHwAPI.findUserHwTeacher(condi);
				for(UserHwTeacher t:teacherList){
					lesResRuleRelMapperp.delHwTeacherById(t.getId());
					lesResRuleRelMapperp.delHwBeByHwId(t.getId());
				}				
			}
		}		
	}
	
	@Transactional(timeout=60)
	private void insertUserNextLesson(String userId) throws Exception{
		User user=userAPI.selectByUserId(userId);				
		//获取下一个课程，是否已完成所有课程
		String nextLessonId=userLessonProgressAPI.getUserNextLesson(user.getId(),user.getClassId());
		
		if(!StringUtils.isEmpty(nextLessonId)){
			Lesson nextLesson=lessonService.selectByPrimaryKey(nextLessonId);
			//当前的课程主键
			LessonResourceRuleRelation rel=selectByLessonId(nextLessonId);
			//资源
			ResourceDetailDTO resource=resourceService.selectByPrimaryKey(rel.getResourceId());
			String resourceType=resource.getResourceType();	
			
			UserLessonProgress pro=new UserLessonProgress();
			pro.setId(Sequence.getSequence().getNextId());
			pro.setUserId(user.getId());
			pro.setLessonId(nextLessonId);
			pro.setClassId(user.getClassId());
			pro.setLessonResourceRuleRelationId(rel.getId());
			pro.setResourceType(resourceType);
			pro.setSort(nextLesson.getSort());
			pro.setStatus(UserLessonProgressEnums.status.studying.getValue());
			pro.setCreateTime(new Date());
			lesResRuleRelMapperp.insertUserLessonProgress(pro);
		
		}else if(user.getLearnStatus().equals(UserEnums.learnStatus.trainning.getValue())){
			//完成所有课程，触发毕业证书
			User upUser=new User();
			upUser.setId(user.getId());
			upUser.setLearnStatus(UserEnums.learnStatus.waiting.getValue());
			lesResRuleRelMapperp.updateUserLearnStatus(upUser);
			
			UserLessonProgress pro=new UserLessonProgress();	
			pro.setId(Sequence.getSequence().getNextId());
			pro.setUserId(user.getId());
			pro.setLessonId(UserLessonProgressCons.END_LESSON_ID1);
			pro.setStatus(UserLessonProgressEnums.status.studying.getValue());
			pro.setSort(Long.valueOf(UserLessonProgressCons.END_LESSON_ID1));
			pro.setClassId(user.getClassId());
			pro.setResourceType("");
			pro.setLessonResourceRuleRelationId("");
			pro.setCreateTime(new Date());
			lesResRuleRelMapperp.insertUserLessonProgress(pro);
			
		}

	}
	

}